// pages/TopList/TopList.js
import request from '../../utils/request';
import PubSub from 'pubsub-js'; // 引入 PubSub

Page({
  data: {
    toplist: {
      coverImgUrl: '', // 榜单封面
      name: '', // 榜单名称
      updateTime: '', // 更新日期
      playCount: 0 // 播放量
    },
    songList: [], // 歌曲列表
    currentIndex: 0 // 当前播放的歌曲索引
  },

  onLoad(options) {
    const id = options.id; // 从页面跳转时传入的 id
    if (id) {
      this.getToplistDetail(id); // 获取榜单详情
      this.getToplistSongs(id); // 获取榜单歌曲列表
    } else {
      wx.showToast({
        title: '未接收到榜单 ID',
        icon: 'none'
      });
    }

    // 订阅 switchType 事件
    PubSub.subscribe('switchType', (msg, type) => {
      this.handleSwitchSong(type); // 处理歌曲切换
    });
  },

  // 获取榜单详情
  async getToplistDetail(id) {
    try {
      const res = await request('/playlist/detail', { id });
      if (res.code === 200) {
        const playlist = res.playlist;
        this.setData({
          toplist: {
            coverImgUrl: playlist.coverImgUrl,
            name: playlist.name,
            updateTime: this.formatDate(playlist.updateTime),
            playCount: playlist.playCount
          }
        });
      } else {
        wx.showToast({
          title: '获取榜单详情失败',
          icon: 'none'
        });
      }
    } catch (error) {
      console.error('获取榜单详情失败:', error);
      wx.showToast({
        title: '获取榜单详情失败',
        icon: 'none'
      });
    }
  },

  // 获取榜单歌曲列表
  async getToplistSongs(id) {
    try {
      const res = await request('/playlist/detail', { id });
      if (res.code === 200) {
        const tracks = res.playlist.tracks;
        const songList = tracks.map(track => ({
          id: track.id,
          name: track.name,
          ar: track.ar,
          al: track.al,
          hot: Math.floor(Math.random() * 100) // 模拟热度值
        }));
        this.setData({ songList });
      } else {
        wx.showToast({
          title: '获取歌曲列表失败',
          icon: 'none'
        });
      }
    } catch (error) {
      console.error('获取歌曲列表失败:', error);
      wx.showToast({
        title: '获取歌曲列表失败',
        icon: 'none'
      });
    }
  },

  // 格式化日期
  formatDate(timestamp) {
    const date = new Date(timestamp);
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');
    return `${month}月${day}日`;
  },

  // 播放歌曲
  playSong(e) {
    const id = e.currentTarget.dataset.id;
    const { songList } = this.data;
    const currentIndex = songList.findIndex(song => song.id === id); // 获取当前歌曲的索引
    this.setData({ currentIndex }); // 更新当前索引

    wx.navigateTo({
      url: `/pages/Song/Song?ids=${id}&index=${currentIndex}&songList=${JSON.stringify(songList)}`
    });
  },

  // 处理歌曲切换
  handleSwitchSong(type) {
    const { songList, currentIndex } = this.data;
    let newIndex = currentIndex;

    if (type === 'prev') {
      newIndex = currentIndex === 0 ? songList.length - 1 : currentIndex - 1; // 上一首
    } else if (type === 'next') {
      newIndex = currentIndex === songList.length - 1 ? 0 : currentIndex + 1; // 下一首
    }

    this.setData({ currentIndex: newIndex }); // 更新当前索引
    const nextSongId = songList[newIndex].id; // 获取下一首歌曲 ID
    wx.navigateTo({ url: `/pages/Song/Song?ids=${nextSongId}&index=${newIndex}&songList=${JSON.stringify(songList)}` }); // 跳转到新歌曲页面
  },

  // 跳转到评论页
  goToComment(e) {
    const songId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/Comment/Comment?type=0&id=${songId}`
    });
  }
});